package com.xiang.publicdemo.module1.controller;

import com.xiang.publicdemo.common.web.R;
import com.xiang.publicdemo.module1.entity.AbstractEntity;
import com.xiang.publicdemo.module1.service.IAbstractService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

@Slf4j
public abstract class AbstractController<E extends AbstractEntity> {

    @Autowired
    protected IAbstractService service;

    abstract String getUIPrefix();

    @GetMapping("/tolist")
    public String toList(Model model) {
        return getUIPrefix() + "list";
    }

    @RequestMapping("/list")
    @ResponseBody
    public R list() {
        return R.success();
    }

    @RequestMapping("/toadd")
    public String toAdd(Model model) {
        return getUIPrefix() + "edit";
    }

    @RequestMapping("/toedit")
    public String toEdit(Model model, String id) {
        model.addAttribute(id);
        return getUIPrefix() + "edit";
    }

    @RequestMapping("/add")
    @ResponseBody
    public R add(Model model, E e) {
        log.debug("this is a test add");
        AbstractEntity result = service.add(e);
        if (Objects.isNull(result.getId())) {
            return R.error();
        }
        return R.success().data(result);
    }
}
